<?php

function operator_get_by_id($id) {
  $operator = database_get_by_id('operators', $id);
  return $operator;  
}

function operator_is_email_exists($email) {
  $query = "SELECT * FROM `operators` WHERE `email` = '$email'";
  $operators = database_get_assoc($query);
  return !empty($operators);
}

function operators_is_auth() {
  return !empty($_SESSION['account']);  
}

function operators_get_online() {
  $outdate  = gmmktime() - CFG_PING_INTERVAL;
  $query    = "SELECT * FROM `operators` WHERE `timestamp` > $outdate";
  $result   = database_get_assoc($query);
  
  return $result;
}

function operators_update_visitors_counter($administratorId) {
  $query = "UPDATE `operators` SET `visitorsCount` = (SELECT COUNT(*) FROM `visitors` WHERE `administratorId` = `operators`.`id`) WHERE `operators`.`id` = $administratorId";
  database_query($query);
}

function operators_get_account() {
  if (empty($_SESSION['account'])) {
    throw new Exception('Operator not loged in');
  }
  
  return $_SESSION['account'];
}

function operators_get_all($administratorId) {
  $query = "SELECT * FROM `operators` WHERE `administratorId` = $administratorId";
  $operators = database_get_assoc($query);
  
  return $operators;
}

function operators_login($email, $password) {
  $query  = "SELECT * FROM `operators` WHERE `email` = '$email' AND `password` = '$password'";
  $result = database_query($query);
  
  if (mysql_num_rows($result) == 0) {
    unset($_SESSION['account']);
    throw new Exception('Unable to login');
  }
  
  $account = mysql_fetch_assoc($result);
  $_SESSION['account'] = $account;
  
  return $account;
}

function operators_register($name, $email, $password, $administratorId = null) {
  $query  = "REPLACE INTO `operators` (`name`, `email`, `password`, `administratorId`) 
  VALUES ('$name', '$email', '$password', $administratorId)";
  
  $result = database_query($query);  
  $id     = mysql_insert_id();
  
  return $id;
}

function operators_ping() {
  $id     = operators_get_id();
  $gmtime = time();
  $query  = "UPDATE `operators` SET `timestamp` = $gmtime WHERE `id` = $id";
  mysql_query($query);
  
  $data['operatorId']     = $id;
  $data['pingDatetime']   = date('Y-m-d H', $gmtime);
  $data['pingTimestamp']  = $gmtime;
  
  database_replace('operators_log', $data);
}

function operators_get_log() {
  $query  = "SELECT * FROM `operators_log` ORDER BY `pingDatetime` DESC";
  $log    = database_get_assoc($query);
  
  return $log;  
}

function operators_get_id() {
  $account = operators_get_account();
  return $account['id'];
}